   var metadata = "";
   /**
    *保存基本信息 
    */
function saveDB() {
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	$('#inputForm').ajaxForm({
			type : "POST",
			beforeSubmit : function() {
				$("#saveBtn").html("处理中...").attr("disabled", "disabled");
				$("#testBtn").attr("disabled", "disabled");
				$("#sbmBtn").attr("disabled", "disabled");
   			},
			url : _ctx + "/data_source/data_source_basic_info_save.do",
			async : true,
			cache : false,
			data : {
				dbType : $("#dbType").val(),
				driverName : $("#driverName").val(),
				url : $("#url").val(),
				userName : $("#userName").val(),
				password : $("#password").val()
			},
			success : function(resp) {
				if (resp.status == 1) {
					isExit = false;
					parent.ui.msg(resp.msg, 1);
					ui.go(_ctx + '/data_source/data_source_list.do');
				} else {
					parent.ui.msg(resp.msg, 0);
				}
				$("#sbmBtn").removeClass("disabled").attr("disabled", null);
				$("#testBtn").removeClass("disabled").attr("disabled", null);
				$("#saveBtn").html("保存基本信息").removeClass("disabled").attr("disabled", null);
			},
			error : function() {
				parent.ui.msg("系统异常,操作失败", 0);
				$("#sbmBtn").removeClass("disabled").attr("disabled", null);
				$("#testBtn").removeClass("disabled").attr("disabled", null);
				$("#saveBtn").html("保存基本信息").removeClass("disabled").attr("disabled", null);
			}
		
	});
}   
   /**
    *数据源测试 
    */
function testDB() {
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	var checkReturn = $('#inputForm').checkForm(null, false);
	if (checkReturn) {
		$("#testBtn").html("处理中...").attr("disabled", "disabled");
		$("#saveBtn").attr("disabled", "disabled");
		$("#sbmBtn").attr("disabled", "disabled");
		$.ajax({
			type : "POST",
			url : _ctx + "/data_source/data_source_test.do",
			async : true,
			cache : false,
			data : {
				dbType : $("#dbType").val(),
				driverName : $("#driverName").val(),
				url : $("#url").val(),
				userName : $("#userName").val(),
				password : $("#password").val()
			},
			success : function(resp) {
				if (resp.status == 1) {
					$("#exDataBtn").attr("disabled", null);
					parent.ui.msg(resp.msg, 1);
				} else {
					parent.ui.msg(resp.msg, 0);
				}
				$("#testBtn").html("测试连接").removeClass("disabled").attr("disabled", null);
				$("#saveBtn").attr("disabled", null);
				$("#sbmBtn").attr("disabled", null);
			},
			error : function() {
				parent.ui.msg("系统异常,操作失败", 0);
				$("#sbmBtn").removeClass("disabled").attr(
						"disabled", null);
				$("#testBtn").html("测试连接").removeClass("disabled")
						.attr("disabled", null);
				$("#saveBtn").attr("disabled", null);
			}
		});
	}
}

/**
 * 抽取元数据
 */
function extractMetadata() {
	var topH = $(parent.document).scrollTop();
	$('#inputForm input').tooltip();
	$('#inputForm').checkForm();
	var checkReturn = $('#inputForm').checkForm(null, false);
	var flag = '${ifAgainExtra}';
	if(flag == false){
		parent.ui.msg("已有数据映射和此数据源关联，不能重新抽取元数据！", 0);
	}else{
		parent.ui.confirm('重新抽取将导致已配置的数据源结构信息被覆盖，是否重新抽取?',function(){
			if (checkReturn) {
				$("#exDataBtn").html("处理中...").attr("disabled", "disabled");

				$("#sbmBtn").attr("disabled", "disabled");
				$.ajax({
					type : "POST",
					url : _ctx + "/data_source/extract_meta_data.do",
					async : true,
					cache : false,
					data : {
						dbType : $("#dbType").val(),
						driverName : $("#driverName").val(),
						url : $("#url").val(),
						userName : $("#userName").val(),
						password : $("#password").val()
					},
					success : function(resp) {
						if (resp.status == 1) {
							metadata = resp.data;
							//解析数据库元数据
							parseTable(metadata);
							$("#sbmBtn").removeClass("disabled").attr("disabled", null);
							parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度
							$(parent.document).scrollTop(topH);//滚动条定位
							$(".chosen-select").trigger("chosen:updated"); 
							parent.ui.msg(resp.msg, 1);
						} else {
							$("#metadata").css("display","none");
							$("#sbmBtn").removeClass("disabled").attr("disabled", "disabled");
							parent.ui.msg(resp.msg, 0);
						}
						$("#exDataBtn").html("重新抽取元数据").removeClass(
								"disabled").attr("disabled", null);
					},
					error : function() {
						parent.ui.msg("系统异常,操作失败", 0);
						$("#metadata").css("display","none");
						$("#sbmBtn").removeClass("disabled").attr("disabled", "disabled");
						$("#exDataBtn").html("重新抽取元数据").removeClass(
								"disabled").attr("disabled", null);
					}
				});
			}
		});
	}
}

var ifSbm = true;

function ifSbms(){
	if(ifSbm == false){
		return false;
	}else{
		return true;
	}
}

/**
 * 提交
 */
function submitBtn(){	
	submitTableInfo();
	$('#inputForm').checkForm(ifSbms);
	$('#inputForm input').tooltip();

	$('#inputForm').ajaxForm({
		url : _ctx + "/data_source/update_data_source.do",
		type : "POST",
		dataType : "json",
		beforeSubmit : function() {
			$("#sbmBtn").html("处理中...")
					.attr("disabled", "disabled");
			$("#testBtn").attr("disabled", "disabled");
		},
		data: {
			tbInfoList:JSON.stringify(tbInfoList),
			tbColInfoList:JSON.stringify(tbColInfoList)
		},
		success : function(resp) {
			if (resp.status == '1') {
				isExit = false;
				parent.ui.msg(resp.msg, 1);
				ui.go(_ctx + '/data_source/data_source_list.do');
			} else {
				$("#sbmBtn").html("提交").removeClass("disabled").attr("disabled", null);
				$("#testBtn").removeClass("disabled").attr("disabled", null);
				parent.ui.msg(resp.msg, 0);
			}
			$("#sbmBtn").html("提交").removeClass("disabled").attr("disabled", null);
			$("#testBtn").removeClass("disabled").attr("disabled",null);
		},
		error : function(resp) {
			parent.ui.msg('请求发送失败', 0);
			$("#sbmBtn").html("提交").removeClass("disabled").attr("disabled", null);
			$("#testBtn").removeClass("disabled").attr("disabled",null);
		}
	});
}

var metadataMap = {};
var fkTableNameOption = ""; 
var fkTablecolNameOption = "";
var lastSelectTable = "";
/**
 * 解析元数据
 */
function parseTable(metadata){
	
	//获取未重新抽取之前的tableid
	var table_tbodys = $("tbody");
   	var tableMap = {};
	for(var i = 0; i<table_tbodys.length; i++){
		//表信息
		
		var table_tbody = table_tbodys[i];
		var table_id = table_tbody.getAttribute("tableId");
		var table_name = table_tbody.getAttribute("id");
		tableMap[table_name] = table_id;
	}
	//重新抽取之后表信息
	var tableListStr = "";//所有表名的下拉列表
	$("tbody").remove();
	metadataMap = {};
	var tableIndex = "1"+"/"+metadata.length;
	$("#tableIndex").html(tableIndex);
	var context = "";
	$("#metadata").css("display","");
	$("#tableObject").html("");
	for(var i=0;i< metadata.length;i++){
		metadataMap[metadata[i].tableName] = metadata[i];//设置map的key 和 value
		var tableName = metadata[i].tableName;
		var tableComment = "";
		if(metadata[i].tableComment != null){
			tableComment = metadata[i].tableComment;
		}
		var tableId = getUuid();
		if(tableMap[tableName]!="" && tableMap[tableName]!=null && tableMap[tableName]!="undefined"){
			tableId = tableMap[tableName];
		}
		//加载表格信息
		if(i == 0){
			tableListStr += "<option selected = 'selected' table_index='"+(i+1)+"'>"+ tableName +"</option>";
			context += " <tbody id = '"+tableName+"' name = '"+tableName+"' tableId='"+tableId+"' schema='"+metadata[i].schema+"' tableindex='' tableComment = '"+tableComment+"'> ";
			lastSelectTable = tableName;
			$("#schemaId").html(metadata[i].schema);
		}else{
			tableListStr += "<option table_index='"+(i+1)+"'>"+ tableName +"</option>";
			context += " <tbody id = '"+tableName+"' name = '"+tableName+"' tableId='"+tableId+"' schema='"+metadata[i].schema+"' style='display: none;' tableindex='' tableComment = '"+tableComment+"'> ";
		}
		var tableInfoVo = metadata[i];
		var tableCols = tableInfoVo.tableColVos;
		for(var j = 0;j < tableCols.length; j++){
			var isPk = "";
			var fkTableName = "";
			var fkTablecolName ="";
			var fkTableNameStr = "";
			var fkTablecolNameStr ="";
			var isIcStr = "";
			var colPk = tableCols[j].isPk;
			var colName = tableCols[j].colName;
			var colComment = tableCols[j].colComment;
			var colType = tableCols[j].colType;
			var colDefault = tableCols[j].colDefault;
			var fkTableName = tableCols[j].fkTableName;
			var fkTablecolName = tableCols[j].fkTablecolName;
			var colCommentStr = "";
			if(colComment == null){
				colComment = "";
			}
			if(colDefault == null){
				colDefault = "";
			}
			if(colComment != null && colComment.length>7){
				colCommentStr = colComment.substring(0,7)+"...";
			}else{
				colCommentStr = colComment;
			}
			getFkTableAndColByTableName(tableName,fkTableName,fkTablecolName);//调用函数，获取外键及外键表
			 //设置主键或唯一键
			if(colPk == 1){
		    	isPk = "<input type='checkbox' id='colPk' value='1' checked='checked' onclick='checkboxChange(this)'>";
		    }else{
		    	isPk = "<input type='checkbox' id='colPk' value='0' onclick='checkboxChange(this)'>";
		    }
			//设置外键表及外键列
			if(colPk != 1){
				fkTableNameStr = "<select style='width: 150px;' name='fkTableName' id='fkTableName' onchange='changefkTable(this)'>"
						        + fkTableNameOption
					            +"</select>";
			    fkTablecolNameStr = "<select style='width: 150px;' name='fkTablecolName' id='fkTablecolName' >"
			                       + fkTablecolNameOption
		                           +"</select>" ;   
                   var str = "number,int,tinyint,decimal,float,double,bigint,numeric"
                             +",timestamp,timestamp with local time zone,timestamp with time zone"
                             +",date,datetime,time";              
	            if(str.toUpperCase().indexOf(colType.toUpperCase())>=0){                   
			    	isIcStr = "<input type='radio' id='' value='0' onclick='radioChange(this)'>";  
	            }	
			}else{
				fkTableNameStr = "<select style='width: 150px;' name='fkTableName' id='fkTableName' onchange='changefkTable(this)' hidden='true'>"
						        + fkTableNameOption
					            +"</select>";
			    fkTablecolNameStr = "<select style='width: 150px;' name='fkTablecolName' id='fkTablecolName' hidden='true'>"
			                       + fkTablecolNameOption
			                       +"</select>" ;   
			       var str = "number,int,tinyint,decimal,float,double,bigint,numeric"
			                 +",timestamp,timestamp with local time zone,timestamp with time zone"
			                 +",date,datetime,time";              
			    if(str.toUpperCase().indexOf(colType.toUpperCase())>=0){                   
			    	isIcStr = "<input type='radio' id='' value='0' onclick='radioChange(this)' hidden='true'>";  
			    }	
			}
			context += " <tr id ='"+colName+"Tr"+"'>"
			         + "    <td hidden='' id='col_id' name = 'col_id'>"+getUuid()+"</td>"
			         + "    <td class='center'>"+(j+1)+"</td>"
			         + "    <td id = 'colName' name = 'colName' >"+colName+"</td>"
			         + "    <td id = 'colComment' name = 'colComment' >"
			         + "      <span class='tipMe' title='"+colComment+"'>"+colCommentStr+"</span>"
			         + "    </td>"
			         + "    <td id = 'colType' name = 'colType' >"+colType+"</td>"
			         + "    <td id = 'colDefault' name = 'colDefault' >"+colDefault+"</td>"
			         + "    <td class='center' id = 'isPk' name ='isPk'>" +isPk+ "</td>"
			         + "    <td >" +fkTableNameStr + "</td>"
			         + "    <td >" +fkTablecolNameStr + "</td>"
			         + "    <td class='center' id = 'isIc' name = 'isIc'>"
			         +           isIcStr
			         + "    </td>"
			         + " </tr>";
			         
		}
		context += " </tbody>";
	}
	$("#tableObject").append(tableListStr);
	$("table thead").after(context);
}

/**
 * 获取外键表和外键值
 */
function getFkTableAndColByTableName(tableName,fkTableName,fkTablecolName){
	fkTableNameOption = "<option value=''>请选择</option>";
	fkTablecolNameOption = "<option value=''>请选择</option>";
	//拼外键表和外键列
	for(var ii=0;ii< metadata.length;ii++){
		var tableName1 = metadata[ii].tableName;
		var cols = metadata[ii].tableColVos;
		if(fkTableName != null && fkTableName == tableName1){
				fkTableNameOption += "<option value = '"+ tableName1 +"' selected = 'selected'>"+ tableName1 +"</option>";
				for(var j = 0;j<cols.length;j++){
					var colName = cols[j].colName;
					if(fkTablecolName != null && fkTablecolName == colName){
						fkTablecolNameOption += "<option value = '"+ colName +"' selected = 'selected'>"+ colName +"</option>";
					}else{
						fkTablecolNameOption += "<option value = '"+ colName +"'>"+ colName +"</option>";
					}
				}

		}else{
			if(tableName1 != tableName){
				fkTableNameOption += "<option value = '"+ tableName1 +"'>"+ tableName1 +"</option>";
				/* if(fkTablecolName == null){
					for(var j = 0;j<cols.length;j++){
						var colName = cols[j].colName;
						fkTablecolNameOption += "<option value = '"+ colName +"'>"+ colName +"</option>";
					}
				} */
			}
		}
	}
} 

/**
 * 改变表名所触发的事件(表对象下拉列表)
 */
function changeTableInfo(sel){
	var topH = $(parent.document).scrollTop();
	$("#"+lastSelectTable).css("display", "none");
	var currentSelectTable = $(sel).find("option:selected").val();
	$("#"+currentSelectTable).css("display", "");
	lastSelectTable = currentSelectTable;
	$("#tableIndex").html($(sel).find("option:selected").attr("table_index")+"/"+'${fn:length(tableInfoList)}');
	$("#schemaId").html($("#"+currentSelectTable).attr("schema"));
	parent.setIframeHeight(parent.document.getElementById("content"));//设置iframe高度
	$(parent.document).scrollTop(topH);//滚动条定位
}

/**
 * 改变外键表触发的事件
 */
function changefkTable(fkTableNameOption){
	var fkTableName = $(fkTableNameOption).find("option:selected").val();
	var tableInfoVo = metadataMap[fkTableName];
	var fkTablecolOption="<option value=''>请选择</option>";
	if(tableInfoVo != "" && tableInfoVo != null && tableInfoVo != "undefined"){
		var tableColVos = tableInfoVo.tableColVos;
		for(var j = 0;j<tableColVos.length;j++){
			fkTablecolOption += "<option>"+tableColVos[j].colName +"</option>";
		}
	}
	//外键列下拉列表设置
	var $select = $(fkTableNameOption).find("option:selected").parent();
	var $td = $select.parent() ;
	var $tr = $td.parent();
	var $child = $tr.find("#fkTablecolName");
	$child.html(fkTablecolOption);
}

/**
 * 改变外键表触发的事件
 */
function changefkTableUpdate(fkTableNameOption){
	var fkTableName = $(fkTableNameOption).find("option:selected").val();
	//外键列下拉列表设置
	var $select = $(fkTableNameOption).find("option:selected").parent();
	var $td = $select.parent() ;
	var $tr = $td.parent();
	var $child = $tr.find("#fkTablecolName");
	var $option = $tr.find("#fkTablecolName").find("option");
	$tr.find("#fkTablecolName").prop("selectedIndex", 0);
	for(var i = 0; i < $option.length; i++){
		var table_name = $($option[i]).attr("table_name");
		if(table_name != null){
			if(fkTableName == table_name){
				//fkTablecolOption += $option[i].outerHTML;
				$option[i].style.display = "";
			}else{
				$option[i].style.display = "none";
			}
		}
	}
}

/*
 *单选框选中与取消
 */
function radioChange(val){
	var tbody = $(val).parent().parent().parent();
 	var isIcNames = $(tbody).find("td[id='isIc']").find("input[checked='checked']");
 	if(isIcNames.length ==1){
		$(isIcNames[0]).attr("value","0");
		$(isIcNames[0]).attr("checked",false);
	}
 	if(isIcNames[0] != val){
 		if($(val).attr("checked")=="checked"){
 			$(val).attr("value","0");
 			$(val).attr("checked",false);
 		}else{
 			$(val).attr("value","1");
 			$(val).attr("checked",true);
 		}
 	}
}

/*
 *复选框选中与取消
 */
function checkboxChange(val){
	if($(val).attr("checked")=="checked"){
		$(val).attr("value","0");
		$(val).attr("checked",false);
		if($(val.parentElement.parentElement).find("#fkTableName").length == 1){
			$(val.parentElement.parentElement).find("#fkTableName").show();
		}
		if($(val.parentElement.parentElement).find("#fkTablecolName").length == 1){
			$(val.parentElement.parentElement).find("#fkTablecolName").show();
		}
		if($(val.parentElement.parentElement).find("#isIc input") != null){
			$(val.parentElement.parentElement).find("#isIc input").show();
		}
	}else{
		$(val).attr("value","1");
		$(val).attr("checked",true);
		if($(val.parentElement.parentElement).find("#fkTableName").length == 1){
			$(val.parentElement.parentElement).find("#fkTableName").hide();
		}
		if($(val.parentElement.parentElement).find("#fkTablecolName").length == 1){
			$(val.parentElement.parentElement).find("#fkTablecolName").hide();
		}
		if($(val.parentElement.parentElement).find("#isIc input") != null){
			$(val.parentElement.parentElement).find("#isIc input").hide();
		}
	}
}

/**
 *生成UUID
 */
function getUuid(){
	var len=32;//32长度
	var radix=16;//16进制
	var chars='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid=[],i;radix=radix||chars.length;if(len){for(i=0;i<len;i++)uuid[i]=chars[0|Math.random()*radix];}else{var r;uuid[8]=uuid[13]=uuid[18]=uuid[23]='-';uuid[14]='4';for(i=0;i<36;i++){if(!uuid[i]){r=0|Math.random()*16;uuid[i]=chars[(i==19)?(r&0x3)|0x8:r];}}}
    return uuid.join('');
} 



var tbInfoList = new Array();  
var tbColInfoList = new Array(); 
   
/**
 * 提交表单时组合元数据信息
 */
function submitTableInfo(){
   	var datasource_id = $("#id").val();
   	
   	var table_tbodys = $("tbody");
   	var colIndex = 0;
	for(var i = 0; i<table_tbodys.length; i++){
		//表信息
		var tbInfo = "";
		var table_tbody = table_tbodys[i];
		var schema = table_tbody.getAttribute("schema");
		var table_name = table_tbody.getAttribute("id");
		var table_comment = table_tbody.getAttribute("tablecomment");
		var table_id = table_tbody.getAttribute("tableId");
		if(table_id == "" || table_id == null || table_id == "undefined"){
			table_id = getUuid();
		}
		//表字段信息
		var table_tr = $(table_tbody).find("tr");
		for(var j = 0; j<table_tr.length; j++){
			var tbColInfo = "";
			var table_td = table_tr[j].children;
			var colName = table_td.colName.innerText;
			var colComment = $(table_td.colComment.children).attr("data-original-title");
			if(colComment == "" || colComment == null || colComment == undefined){
				colComment = "";
			}
			var colType = table_td.colType.innerText;
			var colDefault = $(table_td.colDefault.children).attr("data-original-title");
			if(colDefault == "" || colDefault == null || colDefault == undefined){
				colDefault = "";
			}
			var isPk = "";
			//if($(table_td.isPk).innerHTML != null && $(table_td.isPk.children).length != 0){
				isPk = $(table_td.isPk.children).val();
			//}
			var isIc ="0";
			var col_id = getUuid(); 
			var	fkTableName = "";
			var	fkTablecolName = "";
			if(isPk != 1){
				if($(table_td.isIc.children).length != 0){
					isIc = $(table_td.isIc.children).val();
				}
				if(table_td[7].children.fkTableName != null){
					fkTableName = $(table_td[7].children.fkTableName).find("option:selected").val();
				}
				if(table_td[8].children.fkTablecolName != null){
					fkTablecolName = $(table_td[8].children.fkTablecolName).find("option:selected").val();
				}
				if(fkTableName != "" && fkTableName != null && fkTableName != undefined){
					if(fkTablecolName == "" || fkTablecolName == null || fkTablecolName == undefined){
						alert(table_name+"表没有为外键表列选择外键字段");
						ifSbm = false;
						return;
					}else{
						ifSbm = true;
					}
				}else{
					ifSbm = true;
				}
			}
			tbColInfo = '{"id":"'+col_id+'","dsId":"'+datasource_id+'","tableId":"'+table_id+'","schema":"'+schema+'","tableName":"'+table_name+'","colName":"'+colName+'","colComment":"'+colComment+'","colType":"'+colType+'","isPk":"'+isPk+'","isIc":"'+isIc+'",'
				        +'"fkTableName":"'+fkTableName+'","fkTablecolName":"'+fkTablecolName+'","colDefault":"'+colDefault+'"}';
			tbColInfoList[colIndex] = tbColInfo;
		 	colIndex += 1; 
		}
		tbInfo = '{"id":"'+table_id+'","dsId":"'+datasource_id+'","tableName":"'+table_name+'","schema":"'+schema+'","tableComment":"'+table_comment+'"}';
		tbInfoList[i] = tbInfo;
	}
}    
   
/**
 * 改变数据库类型
 */  
function changeDbType(sel) {
	var selectPption = $(sel).find("option:selected");
	var driverName = selectPption.attr("driverName");
	var linkUrl = selectPption.attr("linkUrl");
	$("#driverName").val(driverName);
	$("#url").val(linkUrl);
}

/**
 * 改变数据源类型
 */
function changeDataSourceType(sel) {
	var selectPption = $(sel).find("option:selected");
	var val = selectPption.val();
	if (val == 1) {
		$("#database").css("visibility", "visible");
	} else {
		$("#database").css("visibility", "hidden");
	}
}

/**
 * 判断是否重新抽取元数据
 */
function ifAgainExtractMetadata(){
	var flag = false;
	var type = $("#type").val();
	var dbType = $("#dbType").val();
	var url = $("#url").val();
	var userName = $("#userName").val();
	var password = $("#password").val();
	var type_ = "${vo.type}";
	var dbType_ = "${vo.dataSourceConfVo.dbType}";
	var url_ = "${vo.dataSourceConfVo.url}";
	var userName_ = "${vo.dataSourceConfVo.userName}";
	var password_ = "${vo.dataSourceConfVo.password}"; 
	if(type != type_ || dbType != dbType_ || url != url_ || userName != userName_ || password != password_){
		flag = true;
	} 
	return flag; 
} 

/**
 * 是否重新抽取元数据
 */
function ifAgainExData(){
	var flag = ifAgainExtractMetadata();
	if(flag){
		$("#exDataBtn").removeClass("disabled").attr(
				"disabled", "disabled");
		$("#testBtn").removeClass("disabled").attr("disabled",
				null);
		$("#sbmBtn").attr("disabled","disabled");
	}
}

function parseDiskData(val){
	if($(val).value == '1'){
		
	}
}